package com.game.framework.orm.jdbc;

import java.sql.*;
import java.util.*;

import org.apache.log4j.Logger;

import com.game.utils.log.Log;

/**
 * ConnectionPoolImpl: 简单连接池实现
 * @author Liyuan
 */

public class ConnectionPoolImpl implements ConnectionPool {
	/** logger */
	private static Logger logger 		= Logger.getLogger(ConnectionPoolImpl.class);
	
	private Integer minSize = 1;
	private Integer maxSize = 3;
	private String	url 	= null;
	
	/** connectionProvider */
	private ConnectionProvider connectionProvider = null;
	/** connectionPool */
	private List<Connection> connectionPool = new ArrayList<Connection>();

	/** 构造函数 */
	public ConnectionPoolImpl(Integer minSize, Integer maxSize, String url) {
		this.minSize = minSize;
		this.maxSize = maxSize;
		this.url 	= url;
		this.init();
	}

	/**
	 * 从连接池取出连接
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException {
		Connection connection = null;
		synchronized (connectionPool) {
			if (!connectionPool.isEmpty()) {
				int last = connectionPool.size() - 1;
				connection = connectionPool.remove(last);
				//logger.debug(poolSize());
				return connection;
			}
		}
		connection = connectionProvider.getConnection();
		//logger.debug(poolSize());
		return connection;
	}

	/**
	 * 释放连接到连接池
	 * @param conn
	 * @throws SQLException
	 */
	public void releaseConnection(Connection conn) throws SQLException {
		synchronized (connectionPool) {
			int currentSize = connectionPool.size();
			if (currentSize < maxSize) {
				connectionPool.add(conn);
				//logger.debug(poolSize());
				return;
			}
		}
		try {
			conn.close();
			//logger.debug(poolSize());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭连接池
	 */
	public void close() {
		Iterator<Connection> iter = connectionPool.iterator();
		while (iter.hasNext()) {
			try {
				iter.next().close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		connectionPool.clear();
		logger.info("连接池关闭.");
	}
	
	/**
	 * finalize
	 */
	protected void finalize() {
		close();
	}
	
	/**
	 * 初始化连接池
	 */
	private void init(){
		try {
			if(url == null || "".equals(url)) return;
			connectionProvider 	= new ConnectionProvider(this.url);
			connectionPool		= new ArrayList<Connection>();
			for(int i=0; i < minSize; ++i){
				connectionPool.add(connectionProvider.getConnection());
			}
		} catch (Exception e) {
			Log.printStackTrace(e);
		}
	}
	
	/** poolSize */
	public Integer poolSize(){
		return connectionPool == null ? 0 : connectionPool.size(); 
	}
	
}
